<?php

namespace app\admin\controller\scanwork;

use app\common\controller\Backend;
use think\Db;

/**
 * 设备管理
 *
 * @icon fa fa-cogs
 * @remark 设备台账、维护保养、故障管理
 */
class Equipment extends Backend
{
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\scanwork\Equipment;
    }

    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['workCenter'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            return json(["total" => $list->total(), "rows" => $list->items()]);
        }
        return $this->view->fetch();
    }
    
    /**
     * 添加
     */
    public function add()
    {
        // 获取工作中心列表
        $workCenterList = Db::name('scanwork_work_center')->where('status', 1)->column('name', 'id');
        $this->view->assign('workCenterList', $workCenterList);
        
        // 加载自定义字段
        $customFieldsHtml = \app\admin\library\CustomFieldHelper::renderFields('equipment');
        $this->view->assign('customFieldsHtml', $customFieldsHtml);
        
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $customFields = $this->request->post("custom_fields/a");
            
            if ($params) {
                $params = $this->preExcludeFields($params);
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                
                $result = false;
                Db::startTrans();
                try {
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    
                    // 保存自定义字段
                    if ($result !== false && $customFields) {
                        \app\admin\library\CustomFieldHelper::saveFieldValues('equipment', $this->model->id, $customFields);
                    }
                    
                    Db::commit();
                } catch (\think\exception\ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\think\exception\PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 维护保养记录
     */
    public function maintenance($ids = null)
    {
        $equipment = $this->model->get($ids);
        if (!$equipment) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isAjax()) {
            $records = Db::name('scanwork_equipment_maintenance_record')
                ->where('equipment_id', $ids)
                ->order('maintenance_date', 'desc')
                ->select();

            return json(['code' => 1, 'data' => $records]);
        }

        $this->view->assign('equipment', $equipment);
        return $this->view->fetch();
    }

    /**
     * 故障记录
     */
    public function fault($ids = null)
    {
        $equipment = $this->model->get($ids);
        if (!$equipment) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isAjax()) {
            $faults = Db::name('scanwork_equipment_fault')
                ->where('equipment_id', $ids)
                ->order('fault_time', 'desc')
                ->select();

            return json(['code' => 1, 'data' => $faults]);
        }

        $this->view->assign('equipment', $equipment);
        return $this->view->fetch();
    }

    /**
     * OEE统计
     */
    public function oee($ids = null)
    {
        $equipment = $this->model->get($ids);
        if (!$equipment) {
            $this->error(__('No Results were found'));
        }

        $startDate = $this->request->get('start_date', date('Y-m-01'));
        $endDate = $this->request->get('end_date', date('Y-m-d'));

        $oeeData = Db::name('scanwork_equipment_oee')
            ->where('equipment_id', $ids)
            ->where('stat_date', 'between', [$startDate, $endDate])
            ->order('stat_date', 'asc')
            ->select();

        if ($this->request->isAjax()) {
            return json(['code' => 1, 'data' => $oeeData]);
        }

        $this->view->assign('equipment', $equipment);
        $this->view->assign('oeeData', $oeeData);
        return $this->view->fetch();
    }
}

